<?php
/**
 * Класс Message - базовый класс сообщений
 *  @author Mike
 */

class Message extends ActiveRecord {
	protected $tableName = 'message';
	protected $pkName = 'ID_message';
	protected $arrSettings = array('created_at' => true, 'author' => true);
	protected $fieldsRules = array (
								'text' => array('min' => 1, 'max' => 50000)
								);
	
	public function getMessageHistory() {
		$objDB = Service_Database::instanse();
		$currentUserId = User_Seance::getId();
		$stmt = "SELECT SUM(`temptable`.`is_read_at` IS NULL AND `temptable`.`ID_user_to`='" . $currentUserId . "') `new_messages`,`user`.`first_name`, `user`.`last_name`, `user`.`ID_user`, `user`.`avatar_filename`,`temptable`.`ID_message`, `temptable`.`text`, `temptable`.`created_at`, `temptable`.`is_read_at`, `temptable`.`ID_user_to`
			     FROM `user` 
 				 RIGHT JOIN (
 							SELECT `message`.*
    						FROM `message`
    						WHERE (`message`.`ID_user`='" . $currentUserId . "' AND `message`.`del_by_user` = 0) OR (`message`.`ID_user_to`='" . $currentUserId . "' AND `message`.`del_by_user_to` = 0)
    						ORDER BY `message`.`created_at` DESC
    					   ) temptable
 				ON (`user`.ID_user = `temptable`.`ID_user`) OR (`user`.ID_user = `temptable`.`ID_user_to`)
 				WHERE `user`.`ID_user` IN (
 											SELECT `ID_user`
											FROM `message`
											WHERE `ID_user_to`='" . $currentUserId . "'
											UNION
											SELECT `ID_user_to` 
											FROM `message`
											WHERE `ID_user`='" . $currentUserId . "'
										  )
 				GROUP BY `user`.`ID_user`
				ORDER BY 5 DESC";
		
		return $objDB->select($stmt);
	}
}
?>